package com.warmheart.controller.login;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.warmheart.entity.access.AccessPermission;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.warmheart.base.annotation.Auth;
import com.warmheart.base.annotation.Duplicate;
import com.warmheart.base.controller.BaseController;
import com.warmheart.base.page.PageInfo;
import com.warmheart.core.enums.ResultCode;
import com.warmheart.core.result.CommonResult;
import com.warmheart.core.util.OperatorUtil;
import com.warmheart.core.util.ParamMapUtil;
import com.warmheart.entity.login.LoginLog;
import com.warmheart.service.login.ILoginLogService;

/**
 * 
 * @ClassName: LoginLogController
 * @Description: 用户登录日志控制器
 * @author ZhangJianyang
 * @date 2025年06月20日 上午10:51:00
 *
 */
@RestController
@RequestMapping("/login/loginLog")
public class LoginLogController extends BaseController {
    
    private static final Logger logger = LoggerFactory.getLogger(LoginLogController.class);

    // 注入用户登录日志service
    @Autowired(required = false)
    private ILoginLogService loginLogService;

    /**
     * 
     * @Title: listData
     * @Description: 查询用户登录日志列表数据
     * @author ZhangJianyang
     * @date 2025年06月20日 上午10:51:00
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @GetMapping("/listDataByCondition")
    public CommonResult<Map<String, Object>> listDataByCondition(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 参数对象
        LoginLog loginLog = new LoginLog();

        // 用户id
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            loginLog.setUserId(userId);
        }

        // 用户名
        String name = ParamMapUtil.getString(jsonMap, "name");
        if (name != null) {
            loginLog.setName(name);
        }

        // 用户登录ip地址
        String ipAddress = ParamMapUtil.getString(jsonMap, "ipAddress");
        if (StringUtils.isNotBlank(ipAddress)) {
            loginLog.setIpAddress(ipAddress);
        }

        // 登录状态
        String status = ParamMapUtil.getString(jsonMap, "status");
        if (StringUtils.isNotBlank(status)) {
            loginLog.setStatus(status);
        }
        
        // 每页记录数
        Integer pageSize = ParamMapUtil.getInteger(jsonMap, "pageSize");
        if (pageSize == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "每页记录数不能为空");
        }
        if (pageSize <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "每页记录数必须大于0");
        }
        loginLog.setPageSize(pageSize);

        // 页码
        Integer pageId = ParamMapUtil.getInteger(jsonMap, "pageId");
        if (pageId == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "页码不能为空");
        }
        if (pageId <= 0) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "页码必须大于0");
        }
        loginLog.setPageId(pageId);

        // 查询列表
        PageInfo<LoginLog> pageInfo = this.loginLogService.queryByList(loginLog);

        List<LoginLog> dataList = pageInfo.getData();
        Map<String,Object> pageMap = new HashMap<String,Object>();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        if (dataList != null && dataList.size() > 0) {
            
            // 整理返回数据
            for (LoginLog tempData : dataList) {
                Map<String, Object> tempMap = new HashMap<String, Object>();
                tempMap.put("id", tempData.getId());
                tempMap.put("userId", tempData.getUserId());
                tempMap.put("name", tempData.getName());
                tempMap.put("ipAddress", tempData.getIpAddress());
                tempMap.put("status", tempData.getStatus());
                tempMap.put("failReason", tempData.getFailReason());
                tempMap.put("createBy", tempData.getCreateBy());
                tempMap.put("cstCreate", tempData.getCstCreate());
                mapList.add(tempMap);
            }
        }
        pageMap.put("dataList", mapList);
        pageMap.put("rowCount", pageInfo.getPager().getRowCount());
        pageMap.put("pageCount", pageInfo.getPager().getPageCount());
        resultMap.put("pageMap", pageMap);
        return CommonResult.success("分页查询用户登录日志数据成功", resultMap);
    }

    /**
     * 
     * @Title: update
     * @Description: 修改用户登录日志数据进入页面
     * @author ZhangJianyang
     * @date 2025年06月20日 上午10:51:00
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @GetMapping("/update")
    public CommonResult<Map<String, Object>> update(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 返回结果
        Map<String, Object> resultMap = new HashMap<String, Object>();
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户登录日志ID不可为空");
        }

        // 校验是否存在
        LoginLog checkLoginLog = loginLogService.queryById(id);
        if (checkLoginLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户登录日志不存在");
        }
        Map<String, Object> tempMap = new HashMap<String, Object>();
        tempMap.put("id", checkLoginLog.getId());
        tempMap.put("userId", checkLoginLog.getUserId());
        tempMap.put("name", checkLoginLog.getName());
        tempMap.put("ipAddress", checkLoginLog.getIpAddress());
        tempMap.put("status", checkLoginLog.getStatus());
        tempMap.put("failReason", checkLoginLog.getFailReason());
        tempMap.put("createBy", checkLoginLog.getCreateBy());
        tempMap.put("cstCreate", checkLoginLog.getCstCreate());
        resultMap.put("dataMap", tempMap);
        return CommonResult.success("获取用户登录日志数据成功", resultMap);
    }

    /**
     * 
     * @Title: addSave
     * @Description: 添加保存用户登录日志数据
     * @author ZhangJianyang
     * @date 2025年06月20日 上午10:51:00
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PutMapping("/addSave")
    public CommonResult<Map<String, Object>> addSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 参数数据
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 数据对象
        LoginLog loginLog = new LoginLog();
        
        // 用户id
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            loginLog.setUserId(userId);
        }

        // 用户名
        String name = ParamMapUtil.getString(jsonMap, "name");
        if (name != null) {
            loginLog.setName(name);
        }
        
        // 用户登录ip地址
        String ipAddress = ParamMapUtil.getString(jsonMap, "ipAddress");
        if (StringUtils.isNotBlank(ipAddress)) {
            loginLog.setIpAddress(ipAddress);
        }
        
        // 登录状态
        String status = ParamMapUtil.getString(jsonMap, "status");
        if (StringUtils.isNotBlank(status)) {
            loginLog.setStatus(status);
        }
        
        // 登录失败原因
        String failReason = ParamMapUtil.getString(jsonMap, "failReason");
        if (StringUtils.isNotBlank(failReason)) {
            loginLog.setFailReason(failReason);
        }

        try {
            OperatorUtil.addOper(loginLog);
            loginLogService.add(loginLog);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("添加用户登录日志失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "添加用户登录日志失败");
        }

        return CommonResult.success("添加用户登录日志成功");
    }

    /**
     * 
     * @Title: updateSave
     * @Description: 修改保存用户登录日志数据
     * @author ZhangJianyang
     * @date 2025年06月20日 上午10:51:00
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @Duplicate(validate = true)
    @PostMapping("/updateSave")
    public CommonResult<Map<String, Object>> updateSave(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        
        // 主键ID
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户登录日志ID不可为空");
        }

        // 是否存在校验
        LoginLog checkLoginLog = loginLogService.queryById(id);
        if (checkLoginLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户登录日志不存在");
        }

        
        // 用户id
        Integer userId = ParamMapUtil.getInteger(jsonMap, "userId");
        if (userId != null) {
            checkLoginLog.setUserId(userId);
        }

        // 用户名
        String name = ParamMapUtil.getString(jsonMap, "name");
        if (name != null) {
            checkLoginLog.setName(name);
        }
        
        // 用户登录ip地址
        String ipAddress = ParamMapUtil.getString(jsonMap, "ipAddress");
        if (StringUtils.isNotBlank(ipAddress)) {
            checkLoginLog.setIpAddress(ipAddress);
        }
        
        // 登录状态
        String status = ParamMapUtil.getString(jsonMap, "status");
        if (StringUtils.isNotBlank(status)) {
            checkLoginLog.setStatus(status);
        }
        
        // 登录失败原因
        String failReason = ParamMapUtil.getString(jsonMap, "failReason");
        if (StringUtils.isNotBlank(failReason)) {
            checkLoginLog.setFailReason(failReason);
        }

        try {
            OperatorUtil.updateOper(checkLoginLog);
            loginLogService.updateIncludeAll(checkLoginLog);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("修改用户登录日志失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "修改用户登录日志失败");
        }

        return CommonResult.success("修改用户登录日志成功");
    }

    /**
     * 
     * @Title: delete
     * @Description: 删除用户登录日志数据
     * @author ZhangJianyang
     * @date 2025年06月20日 上午10:51:00
     * @param request
     * @param response
     * @throws Exception
     */
    @Auth(verifyLogin = true)
    @DeleteMapping("/delete")
    public CommonResult<Map<String, Object>> delete(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        Integer id = ParamMapUtil.getInteger(jsonMap, "id");
        if (id == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该用户登录日志ID不可为空");
        }

        // 是否存在校验
        LoginLog checkLoginLog = loginLogService.queryById(id);
        if (checkLoginLog == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该用户登录日志不存在");
        }

        try {
            loginLogService.deleteById(checkLoginLog.getId());
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除用户登录日志失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除用户登录日志失败");
        }

        return CommonResult.success("删除用户登录日志成功");
    }

    //批量删除
    @Auth(verifyLogin = true)
    @DeleteMapping("/deleteBatch")
    public CommonResult<Map<String, Object>> deleteBatch(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Map<String, Object> jsonMap = getJsonMap(request);
        List<Integer> ids = ParamMapUtil.getIntegerList(jsonMap, "ids");
        if (ids == null) {
            return CommonResult.failed(ResultCode.PARAM_EMPTY, "该批准记录ID不可为空");
        }
        List<LoginLog> loginLogs = loginLogService.queryByIdList(ids);
        if (loginLogs == null) {
            return CommonResult.failed(ResultCode.PARAM_INVALID, "该批准记录不存在");
        }
        try {
            loginLogService.deleteByIdList(ids);
        } catch (Exception e) {
            // 打印错误日志
            logger.error("删除访问记录失败", e);
            return CommonResult.failed(ResultCode.BUSINESS_ERROR, "删除批准记录失败");
        }

        return CommonResult.success("删除批准记录成功");
    }
}
